package edu.utils;

import cn.hutool.core.util.IdUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 云文件存储服务 对接阿里云存储服务，其中包含上传方法，上传后，得到以http开头的可访问链接
 */
public class OssUtil {
    /**
     * 访问链接根目录
     */
    private static final String ACCESS_LINK = "http://programs.ptcc9.top/";

    private static final String END_POINT = "http://oss-cn-beijing.aliyuncs.com";
    private static final String ACCESS_KEY_ID = "LTAI4G1qVrLXqHu3pQqqw5QQ";
    private static final String ACCESS_KEY_SECRET = "C6DQL3BePVmFoyruHQc4SGbAVhJ1gi";

    private static final String BUCKET_NAME = "hlc-programs";
    private static final String ROOT_PATH = "part-time/public-course/";


    /**
     * 创建链接对象
     * @return
     */
    private static OSS createOssObject() {
        return new OSSClientBuilder().build(END_POINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
    }


    /**
     * 获取随机 UUID
     * @return
     */
    private static String randomUUID() {
        return IdUtil.simpleUUID();
    }


    /**
     * 通过 inputStream 上传文件
     * @param inputStream
     * @param path 路径不包括文件名
     * @return
     */
    public static String uploadFile(InputStream inputStream, String path) {
        OSS ossObject = createOssObject();
        //生成最终路径
        String finalPath = ROOT_PATH + path + randomUUID() + ".png";
        //添加文件
        ossObject.putObject(BUCKET_NAME,finalPath,inputStream);
        ossObject.shutdown();
        return ACCESS_LINK + finalPath;
    }

    /**
     * 通过 multipartFile 上传文件
     * @param file
     * @param path 路径不包括文件名
     * @return
     */
    public static String uploadFile(MultipartFile file,String path) {
        OSS ossObject = createOssObject();
        //生成最终路径
        String finalPath = ROOT_PATH + path + randomUUID() + ".png";
        //添加文件
        try {
            ossObject.putObject(BUCKET_NAME,finalPath,new ByteArrayInputStream(file.getBytes()));
        }catch (IOException e) {
            return null;
        }
        ossObject.shutdown();
        return ACCESS_LINK + finalPath;
    }
}
